#include "../../include/MyHredis.h"
#include "../../include/Configuration.h"
#include "../../include/Logger.h"

MyHredis* MyHredis::_pInstance = nullptr;
pthread_once_t MyHredis::_once = PTHREAD_ONCE_INIT;

MyHredis * MyHredis::getInstance()
{
    pthread_once(&_once,init);
    return _pInstance;
}

void MyHredis::connect(const string &host,const int port)
{
    _pConnect = redisConnect(host.c_str(), port);
    if(_pConnect != nullptr && _pConnect->err)
    {
        LogError("Failed to connect redis, host: %s, port: %d!", host, port);
        exit(1);
    }
}

MyHredis::MyHredis()
{
    string ip = Configuration::getInstance()->getConfigValue("REDIS_HOST");
    string port = Configuration::getInstance()->getConfigValue("REDIS_PORT");
    connect(ip, atoi(port.c_str()));
}

void MyHredis::init()
{
    _pInstance = new MyHredis();
    atexit(destory);
}

void MyHredis::destory()
{
    if(_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
}

string MyHredis::get(string key)
{
    _pReply = (redisReply*)redisCommand(_pConnect, "GET %s",
                                        key.c_str());
    string str = _pReply->str;
    freeReplyObject(_pReply);
    _pReply = nullptr;

    return str;
}

void MyHredis::set(string key,string value)
{
    _pReply = (redisReply*)redisCommand(_pConnect, "SET %s %s",
                                        key.c_str(), value.c_str());
    freeReplyObject(_pReply);
    _pReply = nullptr;
}

